package com.zhp.handler;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.zhp.config.TenantConfig;
import com.zhp.tenant.TenantContextHolder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.util.StreamUtils;

import java.util.Objects;

/**
 * @author zhanghp
 * @since 2024/5/16 10:34
 */
@Slf4j
@RequiredArgsConstructor
public class TenantHandler implements TenantLineHandler {

    private final TenantConfig tenantConfig;

    @Override
    public Expression getTenantId() {
        String tenantId = TenantContextHolder.getTenantId();
        log.info("current tenant value is [{}]", tenantId);
        return StrUtil.isBlank(tenantId) ? new NullValue() : new StringValue(tenantId);
    }

    @Override
    public String getTenantIdColumn() {
        return tenantConfig.getTenantField();
    }

    @Override
    public boolean ignoreTable(String tableName) {
        if (IterUtil.isNotEmpty(tenantConfig.getIgnoreTables()) && tenantConfig.getIgnoreTables().contains(tableName)) {
            log.info("[tenant-ignore-tables:{}] reason : config ignore tables", tableName);
            return Boolean.TRUE;
        }
        if (TenantContextHolder.isSkip() || StrUtil.isBlank(TenantContextHolder.getTenantId())) {
            log.info("[tenant-ignore-tables:{}] reason : TenantContextHolder is Empty or TenantContextHolder tenantVal is empty", tableName);
            return Boolean.TRUE;
        }
        return TenantLineHandler.super.ignoreTable(tableName);
    }
}
